﻿Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO

Public Class EntityList
    Private Shared formatter As New BinaryFormatter

    Private mFileName As String
    Public Property Entities As List(Of Entity)

    Public Event Changed()
    Public Event Loaded()

    Public Sub New(ByVal storageFile As String)
        mFileName = storageFile
        Entities = New List(Of Entity)
        LoadEntities()
    End Sub

    Public Sub SaveEntities()
        Using fs As New FileStream(mFileName, FileMode.Create)
            formatter.Serialize(fs, Entities)
        End Using
    End Sub

    Public Sub LoadEntities()
        If IO.File.Exists(mFileName) Then
            Using fs As New FileStream(mFileName, FileMode.Open)
                Entities = formatter.Deserialize(fs)
            End Using
        Else
            Entities = New List(Of Entity)
        End If
        RaiseEvent Loaded()
    End Sub

    Public Sub Add(ByVal name As String, ByVal contents As String)
        Add(New Entity With {.Name = name, .Contents = contents})
    End Sub

    Public Sub Add(ByVal entity As Entity)
        If (From e In Entities Where e.Name = entity.Name).FirstOrDefault Is Nothing Then
            Entities.Add(entity)
            SaveEntities()
            RaiseEvent Changed()
        End If
    End Sub

    Public Sub Remove(ByVal name As String)
        Dim ent As Entity = (From e In Entities Where e.Name = name).FirstOrDefault()
        If Not ent Is Nothing Then
            Entities.Remove(ent)
            SaveEntities()
            RaiseEvent Changed()
        End If
    End Sub
End Class
